package com.huqing.icu.rentuser.service.impl;

import com.huqing.icu.base.PagingDto;
import com.huqing.icu.base.redis.annotation.RedisLock;
import com.huqing.icu.constants.CacheLockConstants;
import com.huqing.icu.rentuser.dao.UserNumPanelDao;
import com.huqing.icu.rentuser.dto.UserNumPanelQueryDto;
import com.huqing.icu.rentuser.model.UserNumPanel;
import com.huqing.icu.rentuser.req.UserNumPanelQueryReq;
import com.huqing.icu.rentuser.service.IUserNumPanelService;
import com.huqing.icu.utils.CopyUtils;
import com.huqing.icu.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @Description 用户活跃接口实现类
 * @Author huqing
 * @Date 2025/9/4 10:21
 **/
@Service
public class UserNumPanelServiceImpl implements IUserNumPanelService {

    @Autowired
    private UserNumPanelDao userNumPanelDao;

    /**
     * 查询列表
     *
     * @param queryReq
     * @return
     */
    @Override
    public PagingDto<UserNumPanel> queryList(UserNumPanelQueryReq queryReq) {
        UserNumPanelQueryDto queryDto = CopyUtils.copy(queryReq, UserNumPanelQueryDto.class);
        int startIndex = PageUtils.getPageStartIndex(queryReq.getPageIndex(), queryReq.getPageSize());
        queryDto.setStartIndex(startIndex);
        Integer count = userNumPanelDao.getNumByCondition(queryDto);
        if (count == 0) {
            return new PagingDto<>(Collections.emptyList(), 0, 0);
        }
        List<UserNumPanel> userNumPanelList = userNumPanelDao.selectByCondition(queryDto);
        return new PagingDto<>(userNumPanelList, PageUtils.getTotalPage(count, queryReq.getPageSize()), count);
    }

    /**
     * 新增用户数和总用户数 +1
     *
     * @param dateList
     * @param typeList
     */
    @RedisLock(key = CacheLockConstants.UserNumPanelPrefix.SAVE_USER_NUM, waitTime = 3000)
    public Integer incrAddUserNumAndUserNum(List<String> dateList, List<Integer> typeList) {
        List<UserNumPanel> userNumPanelList = userNumPanelDao.selectDateByDate(dateList);

        for (int i = 0; i < dateList.size(); i++) {
            String date = dateList.get(i);
            Integer type = typeList.get(i);
            UserNumPanel userNumPanel = userNumPanelList.stream().filter(o -> o.getDate().equals(date)).findFirst().orElse(null);
            if (userNumPanel == null) {
                userNumPanel = new UserNumPanel();
                userNumPanel.setDate(date);
                userNumPanel.setType(type);
                userNumPanel.setActiveUserNum(1);
                userNumPanel.setAddUserNum(1);
                userNumPanel.setActualUserNum(1);
                userNumPanelDao.insert(userNumPanel);
            } else {
                userNumPanelDao.incrAddUserNumAndUserNum(userNumPanel.getId());
            }
        }
        return 1;
    }


}
